<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    title="选择BOM"
    width="1700px"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="160"
    >
      <el-row>
        <el-col :span="17">
            <el-form :model="searchParam" :inline="true">
              <el-form-item label="工厂">
                <el-select
                  @change="changePlant"
                  v-model="searchParam.plantId"
                  placeholder="请选择工厂"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in plants"
                    :key="item.id"
                    :label="item.organizationName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="成品物料">
                <el-input
                  v-model="searchParam.materialCode"
                  placeholder="请选择成品物料"
                  :disabled="!searchParam.plantId"
                  clearable
                  readonly
                  @click="showWorkOrderSelect"
                >
                  <template #append>
                    <el-button
                      type="success"
                      :disabled="!searchParam.plantId"
                      plain
                      @click="showWorkOrderSelect"
                      >选择</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="BOM编号">
                <el-input
                  v-model="searchParam.bomCode"
                  placeholder="请输入BOM编号"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search"
                  ><i-ep-search />搜索</el-button
                >
                <el-button @click="reset"><i-ep-refresh />重置</el-button>
              </el-form-item>
            </el-form>
          <el-card shadow="never" class="table-container">
            <el-table
              ref="bomSelectTableRef"
              v-loading="tableLoading"
              :data="tableData"
              highlight-current-row
              @selection-change="handleSelectionChange"
              row-key="id"
              border
              style="height: 400px"
              :tree-props="{ children: 'nodes', hasChildren: 'hasChildren' }"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column
                label="物料"
                prop="materialCode"
                min-width="100"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="数量"
                prop="matQuantity"
                min-width="100"
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  {{ scope.row.baseQuantity }}
                  {{
                    useDictionary("MeasurementUnit", scope.row.baseQuantityUnit)
                  }}
                </template>
              </el-table-column>
              <el-table-column
                label="工厂"
                prop="plantName"
                min-width="100"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                label="BOM编号"
                prop="bomCode"
                min-width="100"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                label="BOM描述"
                prop="bomDescription"
                min-width="100"
                show-overflow-tooltip
              />
            </el-table>
            <el-pagination
              :background="true"
              :current-page="pageable.pageNum"
              :page-size="pageable.pageSize"
              :page-sizes="[10, 25, 50, 100]"
              :total="pageable.total"
              layout="total, sizes, prev, pager, next, jumper"
              class="mt-[20px]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <div style="float: right">
              <el-button
                type="primary"
                :disabled="ids.length === 0"
                style="margin-bottom: 10px"
                @click="selected"
              >选中 >></el-button
              >
            </div>
          </el-card>
        </el-col>

        <el-col :span="1" />
        <el-col :span="6">
          <div>
            <el-form :inline="true">
              <el-form-item label=" " style="" />
            </el-form>
          </div>
          <el-table
            ref="selectedTableRef"
            :data="formData.selected"
            highlight-current-row
            border
            :cell-style="{ 'text-align': 'center' }"
            style="height: 420px"
          >
            <el-table-column
              label="已选中的BOM"
              align="center"
              prop="materialCode"
              min-width="100"
            >
              <template #header>
                <div style="color: #1d1f24">已选中的BOM</div>
              </template>
            </el-table-column>
            <el-table-column
              label=""
              align="center"
              prop="partnerCode"
              min-width="30"
            >
              <template #header>
                <el-button type="danger" size="small" link @click="removeAll"
                  ><i-ep-delete
                /></el-button>
              </template>
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click="removeItem(scope.row)"
                  ><i-ep-close
                /></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>

    <material-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import useEvent from "@/utils/useEvent";
import { productionVersionHook } from "@/views/mes/produceVersion/hook/productionVersionHook";
import { useDictionary, useTable } from "@/utils/useTable";
import { ElForm } from "element-plus";

defineOptions({
  name: "PRODUCTIONVERSIONMESBOMTREE",
  inheritAttrs: false,
});

const { eventBusEmit, eventBusOn } = useEvent();
const { event, api } = productionVersionHook();
const tree = ref(null);
const treeKey = ref(Math.random());

// 请求参数
const requestApi = "/mes/mesbom/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  bomCode: "",
  plantId: "",
  materialCode: "",
  filterLeaf: true,
};

const deleteParam = {
  api: "/mes/mesbom/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const selectedRows = ref([]);
const ids = ref([]);
const bomSelectTableRef = ref(null);

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  loading: tableLoading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const changePlant = (val) => {
  if (!val) return;
  searchParam.value.materialId = "";
  searchParam.value.materialCode = "";
};
const plants = ref([]);
const getPlants = async () => {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
};

//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
const selectKey = ref(null);
const existKey = ref(null);

const handleSelectionChange = (val) => {
  if (val.length === 0) {
    selectedRows.value = [];
    ids.value = [];
    return;
  }

  const lastSelected = val[val.length - 1];
  selectKey.value = lastSelected.parentBomId;

  const filteredRows = val.filter((row) => row.parentBomId === selectKey.value);

  if (filteredRows.length !== val.length) {
    bomSelectTableRef.value.clearSelection();
    filteredRows.forEach((row) => {
      bomSelectTableRef.value.toggleRowSelection(row, true);
    });
  }

  selectedRows.value = filteredRows;
  ids.value = filteredRows.map((row) => row.id);
};

const removeAll = () => {
  selectedRows.value = [];
  ids.value = [];
  existKey.value = "";
  formData.selected = [];
}

const removeItem = (row) => {
  selectedRows.value = selectedRows.value.filter(
    (item: any) => item.id !== row.id
  );
  formData.selected = formData.selected.filter(
    (item: any) => item.id !== row.id
  );
  ids.value = selectedRows.value.map((item) => item.id);
}

const selected = () => {
  if (existKey.value === selectKey.value){
    const existIds = formData.selected.map((item) => item.id);
    formData.selected = formData.selected.concat(selectedRows.value.filter((item) => !existIds.includes(item.id)))
  } else
    formData.selected = selectedRows.value;
  existKey.value = selectKey.value;
  bomSelectTableRef.value.clearSelection();
}

/** 弹窗显示 **/
const visibleDialog = ref(false);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  bomId: [],
  selected: [],
});
/** rules规则 */
const rules = reactive({
  bomId: [{ required: true, message: "请选择BOM", trigger: "blur" }],
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  resetForm();
  Object.assign(searchParam, searchParamInit);
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.bomId = [];
  treeKey.value = Math.random();
}

const loading = ref(false);

function handleSubmit() {
  closeDialog();
  eventBusEmit(
    event.bomTreeSubmit,
    formData.selected?.map((item) => ({
      materialId: item.materialId,
      materialCode: item.materialCode,
      materialName: item.materialName,
      quantityUnit: item.baseQuantityUnit,
      materialQuantity: item.baseQuantity,
      produceStorageId: item.produceStorageId,
      bomId: item.id,
    }))
  );
  resetForm();
}

onMounted(() => {
  eventBusOn(event.bomTree, (data) => {
    visibleDialog.value = true;
    formData.selected = data?.map((item) => {
      return {
        ...item,
        baseQuantity: item.materialQuantity,
        baseQuantityUnit: item.quantityUnit,
        id: item.bomId,
      };
    });
    existKey.value = data[0]?.parentBomId;
    getPlants();
    getTableList();
  });
});
</script>
